﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommandLib
{
    /// <summary>
    /// execl操作辅助类
    /// </summary>
    public class ExeclHelper
    {
        /// <summary>
        /// 获取表格数据
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string filepath)
        {
            DataTable dt = null;
            if (!string.IsNullOrEmpty(filepath))
            {
                var ext = Path.GetExtension(filepath);
                if (ext.ToLower().Equals(".xls"))
                {
                    dt = ExcelOperation.ImportExcelToDataSet(filepath);
                }
                else if (ext.ToLower().Equals(".xlsx"))
                {
                    dt = EPPlus.GetExcel(filepath);
                }

            }
            return dt;
        }
        /// <summary>
        /// 获取表格数据
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="sheetindex">sheet索引</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string filepath, int sheetindex)
        {
            DataTable dt = null;
            if (!string.IsNullOrEmpty(filepath))
            {
                var ext = Path.GetExtension(filepath);
                if (ext.ToLower().Equals(".xls"))
                {
                    dt = ExcelOperation.ImportExcelToDataSet(filepath, sheetindex, 0);
                }
                else if (ext.ToLower().Equals(".xlsx"))
                {
                    sheetindex = sheetindex < 0 ? sheetindex = 0 : sheetindex;
                    dt = EPPlus.GetExcel(filepath, sheetindex + 1);
                }

            }

            return dt;

        }


        /// <summary>
        /// 导出EXECL
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="filepath">文件路径</param>
        public static void OutToExecl(DataTable dt, string filepath)
        {

            if (!string.IsNullOrEmpty(filepath))
            {
                var ext = Path.GetExtension(filepath);
                if (ext.ToLower().Equals(".xls"))
                {
                    ExcelOperation.DataTableToExcel(dt, filepath);
                }
                else if (ext.ToLower().Equals(".xlsx"))
                {
                    EPPlus.ToExcel(dt, filepath);
                }

            }
        }
    }
}
